#include <common.h>
#include <command.h>
#include <env.h>

int get_bootpart_env(void)
{
    char *bootpart;

    bootpart = env_get("bootpart");
    if (bootpart == NULL)
    {
        printf("Environment variable 'bootpart' is not set.\n");
        return -1;
    }

    printf("bootpart: %s\n", bootpart);
    return 0;
}

static int do_bootpart(struct cmd_tbl *cmdtp, int flag, int argc, char *const argv[])
{
    return get_bootpart_env();
}

U_BOOT_CMD(
    bootpart, 1, 0, do_bootpart,
    "get bootpart environment variable",
    "Prints the value of the bootpart environment variable");

int toggle_bootpart_env(void)
{
    char *bootpart;
    int ret;

    bootpart = env_get("bootpart");
    if (bootpart == NULL)
    {
        printf("Environment variable 'bootpart' is not set.\n");
        return -1;
    }

    printf("Current bootpart: %s\n", bootpart);

    if (strcmp(bootpart, "1:2") == 0)
    {
        ret = env_set("bootpart", "1:3");
        printf("Changed bootpart to 1:3\n");
    }
    else if (strcmp(bootpart, "1:3") == 0)
    {
        ret = env_set("bootpart", "1:2");
        printf("Changed bootpart to 1:2\n");
    }
    else
    {
        printf("bootpart value is not recognized. No changes made.\n");
        return -1;
    }

    if (ret)
    {
        printf("Failed to set bootpart environment variable.\n");
        return -1;
    }

    return 0;
}

static int do_toggle_bootpart(struct cmd_tbl *cmdtp, int flag, int argc, char *const argv[])
{
    return toggle_bootpart_env();
}

U_BOOT_CMD(
    togglebootpart, 1, 0, do_toggle_bootpart,
    "toggle bootpart environment variable between 1:2 and 1:3",
    "Toggles the value of the bootpart environment variable between 1:2 and 1:3");